/*
 * Copyright (c) 2010-2020 DMGIS Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * DMGIS. You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with DMGIS.
 *
 */
package com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl;


import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.common.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.common.domain.MongoResultInfo;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.common.util.MongoDBUtil;
import com.dmgis.qxfw.dataservice.commonservice.utils.StringUtil;
import com.google.common.collect.Maps;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.bson.types.Binary;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

public class MongoService  {
	private String name="";
	private String value="";
	private String collectionName = "";
	private byte[] result = null;
	private String strid = "";
	private boolean bid = false;



	public byte[] selectData(Map<String, Object> queryMap) {
		String dbName= DbConfig.MONGDBNAME;
		String collectionName = (String) queryMap.get("collectionName");
		queryMap.remove("collectionName");
		if (!StringUtil.IsNullOrEmpty((String)queryMap.get("advCode"))){
			dbName = dbName+"_"+queryMap.get("advCode");
			queryMap.remove("advCode");
		}
		// TODO Auto-generated method stub
		byte[] result = null;
		// 无用户密码验证实例
		MongoClient client = MongoDBUtil.instance().getMongoConnect(DbConfig.HOST, DbConfig.PORT);
		// 需要用户密码实例
		MongoCollection<Document> documentMongoCollection = MongoDBUtil.instance().getMongoCollection(client, dbName, collectionName);
		// 插入文档
		MongoCursor<Document> documents = MongoDBUtil.instance().queryDocument(documentMongoCollection, queryMap);
		while (documents.hasNext()) {
			Document document = documents.next();
			Object obj = document.get("data");
			if (obj instanceof Binary) {
				Binary binary = (Binary) obj;
				// 拿到字节数组
				byte[] filebyte = binary.getData();
				result = filebyte;
			}
		}
		client.close();
		return result;
	}

	/**
	 * 根据ID查询数据
	 * @param queryMap
	 * @return
	 */
	public byte[] selectDataByID (Map<String, Object> queryMap){
		String dbName=DbConfig.MONGDBNAME;
		String collectionName = (String) queryMap.get("collectionName");
		String strId = (String) queryMap.get("id");
		queryMap.remove("_id");
		if (!StringUtil.IsNullOrEmpty((String)queryMap.get("advcode"))){
			dbName = dbName+"_"+queryMap.get("advCode");
		}
		byte[] result = null;
		// 无用户密码验证实例
		MongoClient client = MongoDBUtil.instance().getMongoConnect(DbConfig.HOST, DbConfig.PORT);
		// 需要用户密码实例
		MongoCollection<Document> documentMongoCollection = MongoDBUtil.instance().getMongoCollection(client,
				dbName, collectionName);
		// 插入文档
		MongoCursor<Document> documents = MongoDBUtil.instance().queryDocumentById(documentMongoCollection, strId);
		while (documents.hasNext()) {
			Document document = documents.next();
			Object obj = document.get("data");
			if (obj instanceof Binary) {
				Binary binary = (Binary) obj;
				// 拿到字节数组
				byte[] filebyte = binary.getData();
				result = filebyte;
			}
		}
		client.close();
		return result;
	}

	public int insertData(Map<String, Object> insertMap) {
		String dbName=DbConfig.MONGDBNAME;
		String collectionName = (String) insertMap.get("collectionName");
		insertMap.remove("collectionName");
		if (!StringUtil.IsNullOrEmpty((String)insertMap.get("advCode"))){
			dbName = dbName+"_"+insertMap.get("advCode");
			insertMap.remove("advCode");
		}
		// TODO Auto-generated method stub
		try {
			MongoClient client = MongoDBUtil.instance().getMongoConnect(DbConfig.HOST, DbConfig.PORT);
			// 需要用户密码实例
			MongoCollection<Document> documentMongoCollection = MongoDBUtil.instance().getMongoCollection(client,
					dbName, collectionName);
			// 插入文档
			MongoDBUtil.instance().insertDoucument(documentMongoCollection, insertMap);
			client.close();
			return 1;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return 0;
		}
	}

	public String insertDataWithID(Map<String, Object> insertMap) throws UnsupportedEncodingException {
		// TODO Auto-generated method stub
		byte[] bytes = null;
		String dbName=DbConfig.MONGDBNAME;
		String collectionName = (String) insertMap.get("collectionName");
		insertMap.remove("collectionName");
		if (!StringUtil.IsNullOrEmpty((String)insertMap.get("advcode"))){
			dbName = dbName+"_"+insertMap.get("advCode");
			insertMap.remove("advCode");
		}
		if (insertMap.containsKey("data")){
			String byt = (String) insertMap.get("data");
			bytes = byt.getBytes("ISO-8859-1");
			insertMap.put("data",bytes);
		}
		String str_ID = null;
		try {
			MongoClient client = MongoDBUtil.instance().getMongoConnect(DbConfig.HOST, DbConfig.PORT);
			// 需要用户密码实例
			MongoCollection<Document> documentMongoCollection = MongoDBUtil.instance().getMongoCollection(client,
					dbName, collectionName);
			// 插入文档
			str_ID = MongoDBUtil.instance().insertDoucumentWithID(documentMongoCollection, insertMap);
			client.close();
			return str_ID;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return str_ID;
		}
	}

	public long deleteData(Map<String, Object> deleteMap) {
		String dbName=DbConfig.MONGDBNAME;
		String collectionName = (String) deleteMap.get("collectionName");
		deleteMap.remove("collectionName");
		if (!StringUtil.IsNullOrEmpty((String)deleteMap.get("advcode"))){
			dbName = dbName+"_"+deleteMap.get("advCode");
			deleteMap.remove("advCode");
		}
		// TODO Auto-generated method stub
		long count = 0;
		// 删除文档数据
		try {
			MongoClient client = MongoDBUtil.instance().getMongoConnect(DbConfig.HOST, DbConfig.PORT);
			// 需要用户密码实例
			MongoCollection<Document> documentMongoCollection = MongoDBUtil.instance().getMongoCollection(client,
					dbName, collectionName);
			count = MongoDBUtil.instance().deleteDocument(documentMongoCollection, true, deleteMap);
			client.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			count = -1;
		}
		return count;
	}

	public long deleteDataById(Map<String, Object> deleteMap) {
		String dbName=DbConfig.MONGDBNAME;
		String collectionName = (String) deleteMap.get("collectionName");
		deleteMap.remove("collectionName");
		if (!StringUtil.IsNullOrEmpty((String)deleteMap.get("advcode"))){
			dbName = dbName+"_"+deleteMap.get("advCode");
			deleteMap.remove("advCode");
		}
		String strId =(String) deleteMap.get("_id");
		// TODO Auto-generated method stub
		long count = 0;
		// 删除文档数据
		try {
			MongoClient client = MongoDBUtil.instance().getMongoConnect(DbConfig.HOST, DbConfig.PORT);
			// 需要用户密码实例
			MongoCollection<Document> documentMongoCollection = MongoDBUtil.instance().getMongoCollection(client,
					dbName, collectionName);
			count = MongoDBUtil.instance().deleteDocumentById(documentMongoCollection, strId);
			client.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			count = -1;
		}
		return count;
	}
	public Object updateData(HttpServletRequest request, Model model) {
		long count = 0;
		String dbName="";
		Enumeration<String> em= request.getParameterNames();
		Map<String, Object> updateMap = Maps.newHashMap();
		Map<String, Object> updateData = Maps.newHashMap();
		while (em.hasMoreElements()) {
			name = (String) em.nextElement();
			value = request.getParameter(name);
			dbName=DbConfig.MONGDBNAME;
			if("advCode".equals(name))
			{
				if(!"".equals(value)){
					dbName=dbName+"_"+value;
				}
				continue;
			}
			if ("collectionName".equals(name)) {
				collectionName = value;
				continue;
			}else {
				updateMap.put(name, value);
			}
		}
		if (StringUtils.isBlank(collectionName)) {
			return "collectionName参数不能为空，请确定数据库表名称";
		}
		// List<MultipartFile> files = new ArrayList<MultipartFile>();
		try {
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			if (request instanceof MultipartHttpServletRequest) {
				// 将request变成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				Iterator<String> iter = multiRequest.getFileNames();
				// 检查form中是否有enctype="multipart/form-data"
				if (multipartResolver.isMultipart(request) && iter.hasNext()) {
					// 获取multiRequest 中所有的文件名
					while (iter.hasNext()) {
						// 一次遍历所有文件
						MultipartFile file = multiRequest.getFile(iter.next().toString());
						if (file != null) {
							// insertMap.put("fileName", file.getName());
							updateData.put("data", file.getBytes());
							count = updateData(collectionName, updateMap, updateData,dbName);
							// files.add(file);
						}
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		MongoResultInfo resultInfo = new MongoResultInfo();
		resultInfo.setTotal(1);
		resultInfo.setSuccess((int) count);
		return resultInfo;
	}
	public long updateData(Map<String, Object> updateMap,Map<String, Object> updateData) {
		String dbName=DbConfig.MONGDBNAME;
		String collectionName = (String) updateMap.get("collectionName");
		updateMap.remove("collectionName");
		if (!StringUtil.IsNullOrEmpty((String)updateMap.get("advcode"))){
			dbName = dbName+"_"+updateMap.get("advCode");
			updateMap.remove("advCode");
		}
		// TODO Auto-generated method stub
		long count = 0;
		try {
			MongoClient client = MongoDBUtil.instance().getMongoConnect(DbConfig.HOST, DbConfig.PORT);
			// 需要用户密码实例
			MongoCollection<Document> documentMongoCollection = MongoDBUtil.instance().getMongoCollection(client,
					dbName, collectionName);
			count = MongoDBUtil.instance().updateDocument(documentMongoCollection, updateMap, updateData);
			client.close();
		} catch (Exception e) {
			// TODO: handle exception
			count = -1;
		}
		return count;
	}

	public long updateData(String collectionName, Map<String, Object> updateMap, Map<String, Object> updateData,String dbName) {
		// TODO Auto-generated method stub
		long count = 0;
		try {
			MongoClient client = MongoDBUtil.instance().getMongoConnect(DbConfig.HOST, DbConfig.PORT);
			// 需要用户密码实例
			MongoCollection<Document> documentMongoCollection = MongoDBUtil.instance().getMongoCollection(client,
					dbName, collectionName);
			count = MongoDBUtil.instance().updateDocument(documentMongoCollection, updateMap, updateData);
			client.close();
		} catch (Exception e) {
			// TODO: handle exception
			count = -1;
		}
		return count;
	}

	public long existData(Map<String, Object> existMap) {
		String dbName=DbConfig.MONGDBNAME;
		String collectionName = (String) existMap.get("collectionName");
		existMap.remove("collectionName");
		if (!StringUtil.IsNullOrEmpty((String)existMap.get("advcode"))){
			dbName = dbName+"_"+existMap.get("advCode");
			existMap.remove("advCode");
		}

		// TODO Auto-generated method stub
		long count = 0;
		// 删除文档数据
		try {
			MongoClient client = MongoDBUtil.instance().getMongoConnect(DbConfig.HOST, DbConfig.PORT);
			// 需要用户密码实例
			MongoCollection<Document> documentMongoCollection = MongoDBUtil.instance().getMongoCollection(client,
					dbName, collectionName);
			count = MongoDBUtil.instance().countTable(documentMongoCollection, existMap);
			client.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			count = -1;
		}
		return count;
	}

}